package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService{

    @Autowired
    private TravelCommentMongoRepository repository;//简单crud
    @Autowired
    private MongoTemplate template;//高级查询


    public TravelComment save(TravelComment comment) {
        comment.setCreateTime(new Date());
        //如果是评论的评论,需要额外处理
        if (comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE ){
            //查出引用的评论信息
            TravelComment travelComment = repository.findById(comment.getRefComment().getId()).get();
            comment.setRefComment(travelComment);
        }
        repository.save(comment);
        return comment;
    }

    public Page query(TravelCommentQuery qo) {
        //PageResult
        Query query = new Query();

        //设置条件
        if (qo.getTravelId() != -1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        //设置分页对象
        PageRequest pageble = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        //查询总数
        long count = template.count(query, TravelComment.class);

        //分页
        query.with(pageble);

        //查当前页显示的集合
        List<TravelComment> list = template.find(query, TravelComment.class);

        //封装为分页对象
        return new PageImpl(list,pageble,count);
    }

    public Long getCount(Long travelId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("travelId").is(travelId));
        long count = template.count(query, TravelComment.class);
        return count;
    }

}
